﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MoFramework
{
    public class UIManager : BaseManager<UIManager>
    {
        UIManagerData m_Data;
        List<BaseUIForm> m_LoadedForms;
        Dictionary<int, UILayer> m_LayersMap;
        GameObject m_GObjRoot;

        public void Init(UIManagerData dat)
        {
            m_Data = dat;
            m_LoadedForms = new List<BaseUIForm>();
            m_LayersMap = new Dictionary<int, UILayer>();
        }


        protected override void OnStart()
        {
            base.OnStart();
            m_GObjRoot = m_FWMgr.uiRoot.gameObject;
        }

        #region 窗口
        public BaseUIForm Open(string formName)
        {
            BaseUIForm form = null;
            foreach (BaseUIForm loadedForm in m_LoadedForms)
            {
                if (loadedForm.name == formName)
                {
                    form = loadedForm;
                }
            }

            if (form == null)
            {
                foreach (var savedForm in m_Data.forms)
                {
                    if (formName != savedForm.name)
                        continue;
                    form = GameObject.Instantiate<BaseUIForm>(savedForm);
                    form.name = savedForm.gameObject.name;
                    m_LoadedForms.Add(form);
                    break;
                }
            }
            if (form == null)
                return null;
            UILayer layer = GetLayerByForm(form);
            layer.OpenUIForm(form);
            return form;
        }
        #endregion

        #region 层
        UILayer GetLayerByForm(BaseUIForm form )
        {
            UILayer layer=null;
            if(!m_LayersMap.TryGetValue(form.layerID,out layer))
            {
                layer = new UILayer();
                m_LayersMap[form.layerID] = layer;
                layer.Init(m_GObjRoot,form.layerName);
            }
            return layer;
        }
        #endregion

    }
}

